<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\OssProductModel;
use Exception;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class OssProductService extends BaseModelService
{

    /**
     * @var int 上架状态
     */
    CONST STATE_OF_ON_SHELF = 1;

    /**
     * @var int 下架状态
     */
    CONST STATE_OF_OFF_SHELF = 2;

    /**
     * @var int 套餐类型 直连套餐
     */
    CONST TYPE_OF_DIRECT = 1;

    /**
     * @var int 套餐类型 组合套餐
     */
    CONST TYPE_OF_COMPOSER = 2;

    /**
     * @var int 套餐类型 免费套餐
     */
    CONST TYPE_OF_FREE = 3;

    public static function getModel()
    {
        return new OssProductModel;
    }

    /**
     * 编辑条目 新增或者修改
     */
    public static function edit($info)
    {
        $id = $info['id'];
        unset($info['id']);
        if ($id == 0) {
            self::addOssProduct($info);
        } else {
            self::updateOssProduct($id, $info);
        }
        //TODO add code here after data change
        return $info;
    }

    /**
     * 新增条目
     */
    public static function addOssProduct($info)
    {
        //TODO add code here  
        self::add($info);
    }

    /**
     * 修改条目
     */
    public static function updateOssProduct($id, $info)
    {
        $origin  = self::getBase($id);
        if (empty($origin)) {
            throw new ApiException("origin data is not exists", ErrnoPlus::COMMON_INVALID_INPUT);
        }
        //TODO  add code here  

        self::update($id, $info);
    }



    /**
     * 删除条目
     */
    public static function delById($id)
    {
        $origin = self::getBase($id);
        if (empty($origin)) {
            return;
        }
        //TODO  add code here  
        $res = self::del($id);
        return $res;
    }

    /**
     * 获取开放应用已分配的套餐
     */
    public static function getAssignedInfo($openAppId){
        $openApp = OpenAppService::getBase($openAppId);
        if(!$openApp){
            throw new ApiException("开放应用信息不存在");
        }
        $products = self::getAllByFilter([
            'open_app_id' => $openAppId,
        ]);
        unset($openApp['app_secret']);
        return [
            'appInfo' => $openApp,
            "products" => $products,
        ];
    }

    /**
     * 分配
     */
    public static function assign($openAppId,$products){
        if(count($products) < 1){
            return null;
        }
        $origin = self::getAllByFilter([
            'open_app_id' => $openAppId,
        ]);
        $existsIds = Helper::arraySmartUnique(array_column($origin,'id')) ;
        $givenIds = Helper::arraySmartUnique(array_column($products,'id'));
        $difIds = array_diff($existsIds,$givenIds);
        if(count($difIds) >  1){
            throw new ApiException("分配信息丢失部分数据.请检查后再提交",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $difIds = array_values(array_diff($givenIds,$existsIds));
  
        if((count($difIds) == 1 && $difIds[0] != 0) || count($difIds) > 1){
            throw new ApiException("分配信息存在差异.请检查后再提交",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $addProducts = [];
        $updateProducts = [];
        foreach($products as $p){
            if($p['id'] == 0){
                $addProducts[] = $p;
            }
            else{
                $updateProducts[] = $p;
            }
        }
        $addItems = [];
        $tn = time();
        foreach($addProducts as $p){
            $p['open_app_id'] = $openAppId;
            if(!isset($p['sku']) || empty($p['sku'])){
                $p['sku'] = sprintf("%d%d%s%s",date("ymdHis"),mt_rand(100,999),str_pad($openAppId,2,0,STR_PAD_LEFT),str_pad($p['aliyun_cloud_storage_id'],3,0,STR_PAD_LEFT));
            }
            if($p['type'] != self::TYPE_OF_COMPOSER){
                $p['num'] = 1;
            }
            $p['created'] = $tn;
            $p['updated'] = $tn;
            $addItems[] = $p;
        }

        foreach($updateProducts as $p){
            $id = $p['id'];
            $old = Helper::filterOne($origin,['id' => $id]);
            if($p['name'] !== $old['name'] 
                || $p['content'] !== $old['content'] 
                || $p['price'] !== $old['price'] 
                || $p['state'] !== $old['state'] ) {
                    $updateInfo = [               
                        'name' => $p['name'],
                        'content' => $p['content'],
                        'price' => $p['price'],
                        'state' => $p['state'],
                    ];
                self::update($id,$updateInfo);
            }
        }
        
        self::addBulk($addItems);
    }

    /**
     * 页面查询条件
     */
    public static function buildCondition($filter)
    {
        $res = [];
        if (isset($filter['name']) && !empty($filter['name'])) {
            $res['name'] = ['like', '%' . $filter['name'] . '%'];
        }
        if (isset($filter['type']) && !empty($filter['type'])) {
            $res['type'] = $filter['type'];
        }
        //TODO  add code here  
        return $res;
    }

    public static function getBySku($openAppId,$sku){
        $filter = [
            'open_app_id'  => $openAppId,
            'sku' => $sku,
        ];
        return self::getByFilter($filter);
    }
}
